package com.lingchen.boot.controller;

import com.lingchen.boot.job.LofterJob;
import com.lingchen.boot.mapper.SeedMapping;
import com.lingchen.boot.pojo.Seed;
import com.lingchen.boot.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author: lingChen
 * @Date: 2022/5/14
 */
@Slf4j
@RestController
@RequestMapping("/lofter")
public class LofterContoller {

    @Autowired
    SeedMapping seedMapping;
    @Autowired
    LofterJob lofterJob;

    @RequestMapping("/updateSeed")
    public String updateSeed(@RequestParam String url){
        Seed seed = new Seed();
        seed.setUrl(url);
        List<Seed> old = seedMapping.select(seed);
        if (null!= old && old.size() > 0){
            return "已存在";
        }else {
            String body = this.getBody(url);
            seed.setBody(body);
            seedMapping.insert(seed);
        }
        this.startJob();
        return "success";
    }

    @RequestMapping("/startJob")
    public String startJob(){
        try {
            lofterJob.startJob();
        } catch (Exception e) {
            e.printStackTrace();
            return "fail";
        }
        return "success";
    }


    public  String getBody(String url) {
        //String url = "https://tunubf.lofter.com/post/258b4d_1cb401d20";

        String res = HttpClientUtil.sendGetRequest(url);
        Document document = Jsoup.parse(res);
        Element control_frame = document.getElementById("control_frame");
        String src = control_frame.attr("src");
        if (StringUtils.isBlank(src)|| !src.contains("?")){
            log.error("src error ,this html is ->{}",url);
            throw new RuntimeException("src error");
        }
        String s = src.split("\\?")[1];
        s = s.replace("blogId","targetblogid");
        s = s.replace("postId","postid");
        return s;
    }
}
